<?php

/*
* File Name: ./MsgPack.php
* Author: Len
* mail: i@91coder.org
* Created Time: Thu 30 Mar 2017 01:20:10 AM CST
* 字符串二进制解压缩
*/

class MsgPack
{
    static $code = array(
        "username" => "A20",
        "pass" => "A10",
        "age" => "C",
        "birthday" => "I",
        "email" => "A50"
    );

    public static function setCode($key, $val)
    {
        if (is_array($key)) {
            return self::$code = $key;
        }
        self::$code[$key] = $val;
    }

    public static function pack($data)
    {
        $atArr = array();
        foreach ($data as $k => $v) {
            if (empty(self::$code)) return fasle;
            $atArr[] = @pack(self::$code[$k], $v);
        }

        return join("\0", $atArr);
    }

    public static function unpack($str)
    {
        $Arr = explode("\0", $str);
        $atArr = array();
        $i = 0;
        foreach (self::$code as $k => $v) {
            list(, $by) = @unpack($v, $Arr[$i]);
            $atArr[$k] = $by;
            $i++;
        }

        return $atArr;
    }
}
